AssistMe = {}

local version = "0.1.0"

local isAssistMeRunning = false
local assistTarget = ""

function AssistMe.Initialize()
  AssistMe.Disable()

  LibSlash.RegisterSlashCmd("assistme", AssistMe.HandleSlashCommand)	
end

function AssistMe.parseArguments(delimiter,str)
  if (delimiter=='') then 
    return false 
  end
  
  local pos = 0
  local arr = {}
  for st,sp in function() return string.find(str,delimiter,pos,true) end do
    table.insert(arr,string.sub(str,pos,st-1)) 
    pos = sp + 1
  end
  table.insert(arr,string.sub(str,pos))
  return arr
end

function AssistMe.HandleSlashCommand(input)
  local args = AssistMe.parseArguments(" ",input)
  if args[1] == "help" then
    AssistMe.DisplayHelp();
  elseif args[1] == "on" then
    AssistMe.Enable()
  elseif args[1] == "off" then
    AssistMe.Disable()
  elseif args[1] == "status" then
    AssistMe.DisplayStatus()
  elseif args[1] == "target" then
    AssistMe.SetAssistTarget(args[2])
  elseif args[1] == "assist" then
    AssistMe.Assist(assistTarget)
  else
    AssistMe.DisplayHelp();
  end  
end

function AssistMe.DisplayHelp()
  AssistMe.WriteToChat("AssistMe addon Help")
  AssistMe.WriteToChat("Version: "..version)
  AssistMe.DisplayStatus()
  AssistMe.WriteToChat("Usage: /assistme [arguments]")
  AssistMe.WriteToChat("/assistme help - display this help message")
  AssistMe.WriteToChat("/assistme [on/off] - turn the AssistMe addon on/off")
  AssistMe.WriteToChat("/assistme status - display the current status for AssistMe")
  AssistMe.WriteToChat("/assistme target [PC] - set AssistMe to assist the provided Player Character (PC)")
  AssistMe.WriteToChat("/assistme assist - assist the PC set within AssistMe")
end

function AssistMe.Enable()
  isAssistMeRunning = true
  AssistMe.WriteToChat("AssistMe addon is enabled")
end

function AssistMe.Disable()
  isAssistMeRunning = false
  AssistMe.WriteToChat("AssistMe addon is disabled")
end

function AssistMe.DisplayStatus()
  if isAssistMeRunning then
    AssistMe.WriteToChat("Status: AssistMe enabled")
  else 
    AssistMe.WriteToChat("Status: AssistMe disabled")
  end
  AssistMe.WriteToChat("Target: "..assistTarget)
end

function AssistMe.Assist(target)
  SystemData.UserInput.ChatText = L"/assist "..target
  BroadcastEvent( SystemData.Events.SEND_CHAT_TEXT )
end

function AssistMe.SetAssistTarget(target)
  assistTarget = target
  AssistMe.WriteToChat("AssistMe target set to '"..assistTarget.."'")
end

function AssistMe.WriteToChat(text)
  EA_ChatWindow.Print(towstring(text))
end
